def test(fn):
= fn()
codec
= ["Hello","World"]
expected = '5#Hello5#World'
expected_str = codec.encode(expected)
actual_str assert actual_str == expected_str
= codec.decode(actual_str)
actual assert actual == expected
= [""]
expected = '0#'
expected_str = codec.encode(expected)
actual_str assert actual_str == expected_str
= codec.decode(actual_str)
actual assert actual == expected
Problem Source: Leetcode
Problem Description
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector<string> strs) {
// ... your code
return encoded_string;
}
Machine 2 (receiver) has the function:
vector<string> decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2
in Machine 2 should be the same as strs
in Machine 1.
Implement encode
and decode
methods.
You are not allowed to solve the problem using any serialize methods (such as eval
).
Constraints:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] contains any possible characters out of 256 valid ASCII characters.
Follow up: Could you write a generalized algorithm to work on any possible set of characters?
tests
Solution
- Time Complexity:
O(n)
- Space Complexity:
O(1)
from typing import List
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string.
"""
= ''
encoded_str for s in strs:
+= str(len(s)) + '#' + s
encoded_str return encoded_str
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings.
"""
= 0,0
i,l
= []
out while i < len(s):
if s[i] != '#':
= l * 10 + int(s[i])
l += 1
i else:
+1:i+1+l])
out.append(s[i= i + 1 + l
i = 0
l return out
test(Codec)